package com.example.dialog.Tools;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;
//该工具类重写了SQLiteOpenHelper类，用于保存搜索匹配结果
public class DatabaseHelperForSearchResult extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "searchdatabase.db";    //改文件名点①
    private static final int DATABASE_VERSION = 1;

    public DatabaseHelperForSearchResult(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE searchdatabase ("   //改文件名点②
                + "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "searchText TEXT)";
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
    public void saveSearchResult(String searchText) {  // 保存记录
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("searchText", searchText);
        db.insertOrThrow("searchdatabase", null, values);   //改文件名点③
        db.close();
    }

    public List<String> querySearchDataBase(String searchText) {
        List<String> searchResultList = new ArrayList<>();
        String selectQuery = "SELECT * FROM searchdatabase WHERE searchText LIKE '%" + searchText + "%' LIMIT 10;";//改文件名点④

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                String searchResult = cursor.getString(cursor.getColumnIndex("searchText"));
                searchResultList.add(searchResult);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return searchResultList;
    }
}
